package com.xdl.flytest.util.runner;

import com.xdl.flytest.util.docker.DockerEnvironmentConfig;
import com.xdl.flytest.util.docker.DockerManager;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @Auther: 80736
 * @Date: 2019/1/31 15:34
 * @Description:
 */

@Component
public class TestPreProcessor implements TestProcessor {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 运行测试前置处理器
     *
     * @return 容器id
     */
    @Override
    public String process() {

        String containerId = null;
        try {
            containerId = initDockerEnvironment();
        } catch (InterruptedException | IOException e) {
            e.printStackTrace();
        }

        if (containerId != null) {
            return containerId;
        }

        return null;
    }

    /**
     * 初始化测试环境
     */
    private String initDockerEnvironment() throws InterruptedException, IOException {
        // 检查本地测试目录是否存在,不存在则创建
        File file = new File(DockerEnvironmentConfig.JSON_FILE_PATH);
        if (!file.exists()) {

            boolean result = file.mkdirs();
            logger.debug(String.format("mkdir in %s", file.getAbsolutePath()));
            if (!result) {
                throw new RuntimeException("create dir failed,please check");
            }
        }

        // 删除本地测试报告
        List<String> reportFileList = ReportUtil.getReportFileList();
        if (reportFileList.size() > 0) {
            ReportUtil.removeReportDirection();
            logger.debug("clean local report dir");
        }


        // 检查目标容器是否存在，如果不存在则创建，如果存在则返回容器id
        String container = DockerManager.getContainerByName(DockerEnvironmentConfig.IMAGE_NAME);
        if (container == null) {
            String newContainer = DockerManager.createContainer(DockerEnvironmentConfig.CONTAINER_NAME, DockerEnvironmentConfig.IMAGE_NAME);
            if (newContainer != null) {
                logger.debug(String.format("create container:%s successful", newContainer));
                return newContainer;
            } else {
                throw new RuntimeException("测试前置处理器初始化失败，测试中断");
            }
        }

        return container;
    }
}
